/*
 * @Description  : 登录权限
 * @Author       : Keyman
 * @Date         : 2025-11-11 15:45:19
 * @LastEditors  : Keyman
 * @LastEditTime : 2025-11-11 16:52:05
 */

import { useSelector } from "react-redux";
import { useEffect } from "react";
import { useNavigate } from "react-router-dom";

interface Iprops {
  allowed: boolean;
  redirectTo: string;
  children: React.ReactNode;
}

function RequireAuth({ allowed, redirectTo, children }: Iprops) {
  const { token } = useSelector((state: any) => state.authSlice);
  const isLogin = token ? true : false;
  const navigate = useNavigate();

  useEffect(() => {
    // allowed 表示当前路由是否需要登录
    // isLogin 表示当前用户是否登录
    if (allowed !== isLogin) {
      navigate(redirectTo);
    }
  }, [allowed, isLogin, redirectTo]);

  return allowed == isLogin ? children : <></>;
}

export default RequireAuth;
